%% TODO: support quotation, infix ops
%% TODO: write_canonical

:- module(write,['$foo$write'/1]).
:- use_module(token).
:- use_module(compile).

'$foo$write'(Term) :-
 pl_and_ir(Term,IRTerm,[],Variables),
 reverse(Variables,RVariables),name_variables(1,RVariables),
 flatten_ir(IRTerm,Tokens,[]),
 tokenize(Tokens,String,""),
 write_string(String).

flatten_ir(variable(Name)) --> {atom_codes(Name,Codes)}, [variable(Codes)].
flatten_ir(compound(Name,[])) --> {atom_codes(Name,Codes)}, [atom(Codes)].
flatten_ir(compound(Name,[X|Xs])) --> {atom_codes(Name,Codes)}, [atom(Codes)], ['('], flatten_ir(X), flatten_irs(Xs), [')'].

flatten_irs([]) --> [].
flatten_irs([X|Xs]) --> [','], flatten_ir(X), flatten_irs(Xs).
